import subprocess
import sys
import os
import shutil
from Config import AppConfig
def run_gradle_rebuild(project_dir):
    """
    使用 gradlew 执行 clean + build，等效于 Android Studio 的 Rebuild Project
    :param project_dir: Android 项目根目录（包含 gradlew 的目录）
    """
    # 切换到项目目录
    os.chdir(project_dir)

    # 选择 gradlew 脚本（根据操作系统）
    gradlew = './gradlew' if os.name != 'nt' else 'gradlew.bat'

    # 检查 gradlew 是否存在
    if not os.path.exists(gradlew):
        print(f"❌ 错误：未找到 {gradlew}。请确认路径是否正确。")
        return False

    try:
        print(f"🚀 开始执行 Rebuild (clean + build)...")
        print(f"📁 项目目录: {os.getcwd()}")

        # 使用 Popen 实现实时流式输出
        process = subprocess.Popen(
            [gradlew, 'clean', 'build', '-x', 'test', '-x', 'check'],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,  # 合并标准错误输出
            text=True,
            encoding='utf-8',
            errors='replace',
            bufsize=1,  # 行缓冲
            universal_newlines=True
        )

        # 实时读取输出
        while True:
            output = process.stdout.readline()
            if output == '' and process.poll() is not None:
                break
            if output:
                print(output.strip())

        # 获取返回码
        return_code = process.poll()

        if return_code == 0:
            print("✅ Rebuild 成功完成！")
            return True
        else:
            print("❌ Rebuild 失败！返回码:", return_code)
            return False

    except Exception as e:
        print(f"❌ 执行过程中发生异常: {e}")
        return False

def copy_so_2_x1(nativelibs_project_path,x1_project_path):
    """
    将生成的 .so 文件复制到 X1 项目的 libs 目录
    :param project_dir: X1 项目根目录
    """
    # 获取 .so 文件的绝对路径
    so_dir_path = os.path.join(
        nativelibs_project_path, "app/build/intermediates/cxx/Debug"
    )
    so_dir = os.listdir(so_dir_path)
    if(len(so_dir) == 0):
        print("❌ 未找到 .so 文件。请确认项目是否已构建。")
        return False
    so_dir_path = os.path.join(so_dir_path,so_dir[0],"obj/arm64-v8a")
    so_file = os.listdir(so_dir_path)
    x1_so_file = os.path.join(x1_project_path, "app/src/main/jniLibs/arm64-v8a")
    if not os.path.exists(x1_so_file):
        print("jniLibs文件夹未存在,是否自动创建")
    # 创建备份目录（如果不存在）
    if not os.path.exists(AppConfig.backup_path):
            os.makedirs(AppConfig.backup_path)
    # 得到backpu_path的绝对路径
    AppConfig.backup_path = os.path.abspath(AppConfig.backup_path)
    print("备份目录:",AppConfig.backup_path)
    for file in so_file:
        if file.endswith(".so"):
            try:
                so_file_path = os.path.join(so_dir_path, file)
                shutil.copy(so_file_path, os.path.join(x1_so_file,file))
                print(f"文件:{so_file_path}  复制到:{os.path.join(AppConfig.backup_path,file)}")
                shutil.copy(so_file_path, os.path.join(AppConfig.backup_path,file))
            except Exception as e:
                print(f"❌ 复制文件 {file} 失败: {e}")
                return False

def copy_model_2_x1(model_file_path:str,x1_project_path:str):
    new_model_file_path = os.path.join(x1_project_path,"app/src/main/assets/encrypted_model_files/qr",f"{AppConfig.model_name}.dll")
    shutil.copyfile(model_file_path, new_model_file_path)